package com.miya.system.configure;

import cn.hutool.core.collection.CollUtil;
import com.miya.entity.MiyaResponse;
import com.miya.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 全局异常处理程序
 *
 * @author Caixiaowei
 * @date 2022/02/23
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	@ExceptionHandler(value = BusinessException.class)
	public MiyaResponse handler(BusinessException e) {
		log.error(String.format("异常信息===================%s", e.getMessage()), e);
		return MiyaResponse.error(e.getMessage());
	}

	@ExceptionHandler(value = MissingServletRequestParameterException.class)
	public MiyaResponse handler(MissingServletRequestParameterException e) {
		log.error(String.format("异常信息===================%s", e.getMessage()), e);
		return MiyaResponse.error(String.format("入参异常：%s", e.getMessage()));
	}

	/**
	 * 处理请求对象属性不满足校验规则的异常信息
	 *
	 * @param request HttpServletRequest
	 * @param e MethodArgumentNotValidException
	 * @return ExceptionResResult
	 */
	@ExceptionHandler(value = {MethodArgumentNotValidException.class})
	public MiyaResponse handler(HttpServletRequest request, MethodArgumentNotValidException e) {
		log.error(String.format("数据校验异常===================%s", e.getMessage()), e);
		BindingResult result = e.getBindingResult();
		List<FieldError> fieldErrors = result.getFieldErrors();
		StringBuilder builder = new StringBuilder();
		if (CollUtil.isNotEmpty(fieldErrors)) {
			builder.append(fieldErrors.get(0).getDefaultMessage()).append("!");
		}
		log.info(Arrays.toString(fieldErrors.toArray()));
		return MiyaResponse.error(String.format("入参异常：%s", builder.toString()));
	}

	@ExceptionHandler(value = Exception.class)
	public MiyaResponse handler(Exception e) {
		log.error(String.format("异常信息===================%s", e.getMessage()), e);
		return MiyaResponse.error(String.format("服务器内部异常：%s", e.getMessage()));
	}
}
